using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;

namespace RSStoZPL
{
    class ZunePlaylist
    {
        private string title;

        public string Title
        {
            get { return title; }
            set { title = value; }
        }
        private List<ZunePlaylistItem> items = new List<ZunePlaylistItem>();

        public List<ZunePlaylistItem> Items
        {
            get { return items; }
        }

        public void Save(string filename)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(RSStoZPL.Properties.Resources.PlayListTemplate);
            XmlElement titleElement = doc.SelectSingleNode("/smil/head/title") as XmlElement;
            titleElement.InnerText = Title;
            XmlElement seqElement = doc.SelectSingleNode("/smil/body/seq") as XmlElement;
            foreach (ZunePlaylistItem item in Items)
            {
                seqElement.AppendChild(item.ToXmlElement(doc));
            }
            XmlTextWriter writer = new XmlTextWriter(filename, null);
            writer.Formatting = Formatting.Indented;
            doc.Save(writer);
            writer.Flush();
            writer.Close();
        }

        public static string CleanupFilename(string filename)
        {
            string returnFilename = filename;
            foreach (char badChar in Path.GetInvalidFileNameChars())
            {
                int badIndex = returnFilename.IndexOf(badChar);
                while (badIndex >= 0)
                {
                    returnFilename = returnFilename.Remove(badIndex, 1);
                    badIndex = returnFilename.IndexOf(badChar);
                }
            }
            return returnFilename;
        }

        public class ZunePlaylistItem
        {
            private string mediaFile;

            public string MediaFile
            {
                get { return mediaFile; }
                set { mediaFile = value; }
            }
            public ZunePlaylistItem(string mediaFile)
            {
                MediaFile = mediaFile;
            }



            internal XmlElement ToXmlElement(XmlDocument doc)
            {
                XmlElement mediaElement = doc.CreateElement("media");
                XmlAttribute srcAttribute = doc.CreateAttribute("src");
                srcAttribute.Value = MediaFile;
                mediaElement.Attributes.Append(srcAttribute);
                return mediaElement;
            }
        }
    }
}
